from django.core.management.base import BaseCommand
from catalog.models import Book, BookInstance
from django.contrib.auth.models import User
import uuid
from datetime import datetime, timedelta
import random

class Command(BaseCommand):
    help = 'Create book instances (copies) and set some as borrowed'

    def handle(self, *args, **kwargs):
        # 确保有一个测试用户
        user, created = User.objects.get_or_create(
            username='meijiaxue',
            defaults={
                'email': 'test@example.com',
                'first_name': 'Mei',
                'last_name': 'Jiaxue'
            }
        )
        if created:
            user.set_password('testpass123')
            user.save()

        # 获取所有图书
        books = Book.objects.all()
        
        # 为每本书创建1-3个副本
        for book in books:
            num_copies = random.randint(1, 3)
            for _ in range(num_copies):
                status = random.choice(['m', 'o', 'a', 'r'])  # 维护中/已借出/可借阅/预订
                due_back = None
                borrower = None
                
                # 如果状态是"已借出"，设置借阅者和归还日期
                if status == 'o':
                    borrower = user
                    due_back = datetime.now() + timedelta(days=random.randint(1, 30))
                
                BookInstance.objects.create(
                    book=book,
                    imprint=f'本馆藏书 {datetime.now().year}',
                    due_back=due_back,
                    borrower=borrower,
                    status=status,
                    id=uuid.uuid4()
                )

        self.stdout.write(self.style.SUCCESS('Successfully created book instances!')) 